<template>
  <view>
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
      <view class="nav-right-icon">
        <view @tap="handlerSure"> 确定 </view>
      </view>
    </theme-navbar>
    <!-- #endif -->
    <!-- #ifdef H5-WECHAT || H5-EMP -->
    <fab-button :content="fContent" @fabtrigger="fabtrigger" />
    <!-- #endif -->
    <view
      id="taskPoolMapContainer"
      :style="{ width: '100%', height: getMapHeight() }"
    ></view>
    <view class="choose-info">
      <text>已选中</text>
      <text style="font-weight: 600; padding: 0 10rpx">
        {{ selectedRetailers.length }} </text
      >户
    </view>
    <scroll-view scroll-y="true" :style="{ height: getMapHeight() }">
      <u-swipe-action
        v-for="(item, index) in selectedRetailers"
        :key="item.retailerUuid"
        :index="index"
        :show="item.show"
        :options="options"
        style="border-bottom: 1px solid #e5e5e5; padding: 10px 8px"
        @click="handlerDeleteClient(item)"
        @open="handlerOpen(index)"
      >
        <client-item :client="item"></client-item>
      </u-swipe-action>
    </scroll-view>
  </view>
</template>
  
<script>
import certificateService from "@/service/certificate/certificate.service.js";
import ClientItem from "./components/client-item.vue";
import fabButton from "@/components/uni-fab.vue";
import { AMapMixin } from "@/common/AMapMixin.js";
import { SET_MAP_LAT_LON } from "@/config/setting.config.js";

export default {
  components: {
    ClientItem,
    fabButton,
  },
  mixins: [AMapMixin],
  data() {
    return {
      selectedRetailers: [], // 选中的零售户
      markers: [], // 点标记
      retailerIcon: new AMap.Icon({
        size: new AMap.Size(24, 24), // 图标尺寸
        image: require("../../static/check/marker.png"), // Icon的图像
        imageSize: new AMap.Size(24, 24), //,
      }),
      retailerSelectedIcon: new AMap.Icon({
        size: new AMap.Size(24, 24), // 图标尺寸
        image: require("../../static/check/marker_selected.png"), // Icon的图像
        imageSize: new AMap.Size(24, 24), //,
      }),
      searchData: {},
      options: [
        {
          text: "删除",
          style: {
            backgroundColor: "#dd524d",
          },
        },
      ],
      fContent: [
        {
          iconPath: require("@/static/confirm.png"),
          selectedIconPath: require("@/static/confirm.png"),
          text: "确定",
          active: false,
        },
      ],
      isMultiple: false, // 是否多选，默认单选
    };
  },
  onLoad(options) {
    this.isMultiple = options.isMultiple && options.isMultiple == 1;
  },
  mounted() {},
  methods: {
    setRightBtns() {
      let self = this;
      // 设置右侧标题
      // #ifdef H5-DINGDING
      self.$deviceApi.setRight('确定', () => {
        self.handlerSure();
        self.setRightBtns();
      }, true, true);
      // #endif
    },
    fabtrigger(btn) {
      if (btn.index == 0) {
        this.handlerSure();
      }
    },
    handlerOpen(idx) {
      this.selectedRetailers.map((c, i) => {
        c.show = i == idx;
      });
      this.$forceUpdate();
    },
    // 删除选中的客户
    handlerDeleteClient(cItem) {
      this.selectedRetailers = this.selectedRetailers.filter(
        (c) => c.retailerUuid != cItem.retailerUuid
      );
    },
    handlerSure() {
      if (!this.isMultiple && this.selectedRetailers.length > 1) {
        this.$u.toast("只能选择一条零售户!");
        return;
      } else if (!this.selectedRetailers.length) {
        this.$u.toast("请选择零售户!");
        return;
      }
      this.backPrev({
        paramKey: "selectRetailerMap",
        param: this.selectedRetailers,
      });
    },
    getMapHeight() {
      console.log("系统信息", uni.getSystemInfoSync());
      let h = (uni.getSystemInfoSync().windowHeight - 44 - 38) / 2 + "px";
      // #ifdef H5-DINGDING
      // h = uni.getSystemInfoSync().windowHeight / 2 + 'px'
      // #endif
      return h;
    },
    initAmap() {
      if (this.$deviceApi.geolocation) {
        this.$deviceApi.geolocation().then((geo) => {
          this.curPos = [geo.longitude, geo.latitude];
          this.setMapInstance(this.curPos);
        });
      } else {
        this.curPos = SET_MAP_LAT_LON;
        this.setMapInstance(this.curPos);
      }

      let self = this;
      // #ifdef H5-DINGDING || H5-WECHAT
      this.getCurrentLocation().then(
        (res) => {
          self.curPos = [res.lng, res.lat];
          self.setMapInstance([res.lng, res.lat]);
        },
        (err) => {}
      );
      // #endif
    },
    setMapInstance(cords) {
      if (!this.hasInited) return;
      let self = this;
      self.curCords = new AMap.LngLat(cords[0], cords[1]);
      self.amap = new AMap.Map("taskPoolMapContainer", {
        center: self.curCords,
        showControlButton: true,
        zoom: 13,
      });
      AMap.plugin(
        [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.OverView",
          "AMap.MapType",
          "AMap.Geolocation",
        ],
        () => {
          // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
          self.amap.addControl(new AMap.ToolBar());
          // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
          self.amap.addControl(new AMap.Scale());
          // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
          self.amap.addControl(new AMap.Geolocation());
        }
      );
      self.$ownerInstance.callMethod("mapInit", {});
      self.searchMapTasks();
      // 地图缩放
      self.amap.on("zoomend", function () {
        if (self.markers.length > 0) {
          self.amap.remove(self.markers);
        }
        self.searchMapTasks();
      });
      // 地图移动
      self.amap.on("moveend", function () {
        if (self.markers.length > 0) {
          self.amap.remove(self.markers);
        }
        self.searchMapTasks();
      });
    },
    // 获取可视范围的坐标
    getBoundsData() {
      let tampBounds = this.amap.getBounds();
      let northwest = tampBounds.getNorthWest(); // 西北
      let eastsouth = tampBounds.getSouthEast(); // 东南
      this.searchData.latitudeStart =
        northwest.lat > eastsouth.lat ? eastsouth.lat : northwest.lat;
      this.searchData.latitudeEnd =
        northwest.lat > eastsouth.lat ? northwest.lat : eastsouth.lat;
      this.searchData.longitudeStart =
        northwest.lng > eastsouth.lng ? eastsouth.lng : northwest.lng;
      this.searchData.longitudeEnd =
        northwest.lng > eastsouth.lng ? northwest.lng : eastsouth.lng;
    },
    // 查询任务池数据
    searchMapTasks() {
      this.$u.loading("数据加载中...");
      this.getBoundsData();
      certificateService
        .listRetailInScope({
          ...this.searchData,
          licStatus: ["01", "02", "10"],
        })
        .then((dr) => {
          this.$u.hideLoading();
          if (dr.success) {
            this.markers = dr.data.map((retailer) =>
              this.drawerMarker(retailer)
            );
            this.amap.add([...this.markers]);
          } else {
            this.$u.toast(dr.msg);
          }
        })
        .catch((err) => {
          this.$u.hideLoading();
          this.$u.toast(err);
        });
    },
    drawerMarker(retailer) {
      let markerConfig = {
        size: new AMap.Size(24, 24), // 图标尺寸
        position: new AMap.LngLat(retailer.longitude, retailer.latitude),
        title: retailer.companyName,
      };
      let marker = new AMap.Marker(markerConfig);
      marker.retailerUuid = retailer.retailerUuid;
      marker.setIcon(this.retailerIcon);

      marker.on("click", () => {
        // 区分处理标记点击
        let selectArrs = this.selectedRetailers.map(
          (item) => item.retailerUuid
        );
        if (selectArrs.indexOf(retailer.retailerUuid) > -1) {
          this.selectedRetailers = this.selectedRetailers.filter(
            (it) => it.retailerUuid != retailer.retailerUuid
          );
          marker.setIcon(this.retailerIcon);
        } else {
          this.selectedRetailers.push(retailer);
          marker.setIcon(this.retailerSelectedIcon);
        }
      });
      return marker;
    },
  },
};
</script>
  
  <style lang="scss" scoped>
.sticky-header {
  background-color: #fff;
  position: fixed;
  /* #ifdef H5-DINGDING  */
  top: 0px;
  /* #endif */
  /* #ifndef H5-DINGDING  */
  top: 44px;
  /* #endif */
  width: 100%;
  height: 40px;
  z-index: 999;
  padding: $cm-search-padding-row $cm-search-padding-column;
  height: 55px;
  line-height: 30px;
}

.choose-info {
  height: 38px;
  line-height: 38px;
  padding-left: 10px;
  font-size: 16px;
  background-color: #f1f1f1;

  span {
    font-weight: 600;
    margin: 0px 5px;
  }
}
</style>
  